package com.projectx.action.findPassword;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.action.login.LoginActivity2;
import com.projectx.action.talk.TalkListActivity;
import com.projectx.entity.User;
import com.projectx.entity.UserData;
import com.projectx.util.ActivityManage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FindPassword extends AppCompatActivity {
    private String assistAccount;
    private String realName;
    private String username;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManage.addActivity("FindPassword",this);
        setContentView(R.layout.find_password);

        final Intent accountIntent = getIntent();
        username = accountIntent.getStringExtra("accountName");
        final Button next = findViewById(R.id.FindPasswordNext);
        final Button otherWay = findViewById(R.id.OtherWay);
        final EditText assistInput = findViewById(R.id.AssistEditText);
        final TextInputLayout assistInputLayout = findViewById(R.id.AssistEditField);
        final TextView textView = findViewById(R.id.FindXPasswordText);
        final TextView accountText = findViewById(R.id.AccountText);
        final EditText nameInput = findViewById(R.id.NameEditText);
        final TextInputLayout nameInputLayout = findViewById(R.id.NameEditField);
        progressBar = findViewById(R.id.FindProgress);
        progressBar.setVisibility(View.INVISIBLE);

        assistInput.setInputType(InputType.TYPE_CLASS_NUMBER);

        TextPaint textPaint = textView.getPaint();
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setStrokeWidth(2);

        TextPaint textPaint1 = accountText.getPaint();
        textPaint1.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint1.setStrokeWidth(2);
        accountText.setText(username);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                assistAccount = assistInput.getText().toString();
                realName = nameInput.getText().toString();
                if (assistAccount.isEmpty()) {
                    assistInputLayout.setError("请输入有效的学号");
                    assistInputLayout.setError(null);
                } else if(realName.isEmpty()){
                    nameInputLayout.setError("请输入有效的真实姓名");
                    assistInputLayout.setError(null);
                } else {
                    nameInputLayout.setErrorEnabled(false);
                    assistInputLayout.setError(null);
                    try {
                        Long.parseLong(assistAccount);
                    } catch (Exception e){
                        Toast.makeText(FindPassword.this, "学号应为纯数字", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    FutureTask<JSONObject> task = new FutureTask<>(new Callable<JSONObject>() {
                        @Override
                        public JSONObject call() throws Exception {
                            JSONObject getMessage = null;
                            try {
                                Socket socket = new Socket("106.15.192.117", 2333);
                                Gson gson = new Gson();
                                User user = new User();
                                user.setFlag(3);
                                user.setUserName(username);
                                user.setRealName(realName);
                                user.setId(Long.parseLong(assistAccount));
                                String message = gson.toJson(user);
                                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                                dataOutputStream.writeUTF(message);
                                dataOutputStream.flush();
                                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                                String netStr = dataInputStream.readUTF();
                                try {
                                    getMessage = new JSONObject(netStr);
                                } catch (JSONException e) {
                                    Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                                } finally {
                                    dataInputStream.close();
                                    dataOutputStream.close();
                                    socket.close();
                                }

                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                            return getMessage;
                        }
                    });
                    Thread thread = new Thread(task);
                    thread.start();
                    try {
                        JSONObject message = task.get(5, TimeUnit.SECONDS);
                        int code = message.getInt("code");
                        progressBar.setVisibility(View.INVISIBLE);
                        if (code == -1) {
                            assistInputLayout.setError("信息匹配错误");
                            nameInputLayout.setError("信息匹配错误");
                        } else if (code == 0) {
                            //假设以一定方法确定辅助账户正确
                            Intent intent = new Intent(FindPassword.this,LoginActivity2.class);
                            intent.putExtra("accountName",username);
                            intent.putExtra("password",message.getString("data"));
                            ActivityManage.exitActivity("LoginActivity2");
                            startActivity(intent);
                            ActivityManage.removeActivity("FindPassword");
                        }
                    } catch (TimeoutException te) {
                        Toast.makeText(FindPassword.this, "时间戳错误", Toast.LENGTH_SHORT).show();
                    } catch (JSONException je) {
                        Toast.makeText(FindPassword.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        je.printStackTrace();
                    } catch (Exception ne){
                        ne.printStackTrace();
                        Toast.makeText(FindPassword.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                    } finally {
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
        otherWay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alert = new AlertDialog.Builder(FindPassword.this);
                alert.setTitle("你莫得选择");
                alert.setMessage("不支持其他方式，气不气");
                alert.setPositiveButton("好的",null);
                alert.setNegativeButton("好的",null);
                alert.setCancelable(false);
                alert.show();
            }
        });
    }
}
